import * as orm from '@midwayjs/typeorm';
import {
  Configuration,
  App,
  IMidwayApplication,
  Inject,
  ILogger,
  MidwayWebRouterService,
  ILifeCycle,
  MidwayEnvironmentService,
  MidwayFrameworkType,
} from '@midwayjs/core';
import * as koa from '@midwayjs/koa';
// import * as crossDomain from '@midwayjs/cross-domain';
import * as validate from '@midwayjs/validate';
import * as info from '@midwayjs/info';
import * as staticFile from '@midwayjs/static-file';
import * as cron from '@midwayjs/cron';
import * as DefaultConfig from './config/config.default';
import * as LocalConfig from './config/config.local';
import * as ProdConfig from './config/config.prod';
import * as cool from '@cool-midway/core';
import * as upload from '@midwayjs/upload';
import * as socketio from '@midwayjs/socketio';
import * as task from '@cool-midway/task';
import * as view from '@midwayjs/view-ejs';

// import * as rpc from '@cool-midway/rpc';
import { ProcedureGenerator } from './comm/service/procedure.generator';
import { DataSource } from 'typeorm';
import { InjectDataSource } from '@midwayjs/typeorm';
// import { OracleService } from './comm/service/oracle.service'; // 可以不导入，让容器管理

@Configuration({
  imports: [
    // https://koajs.com/
    koa,
    // 是否开启跨域(注：顺序不能乱放！！！) http://www.midwayjs.org/docs/extensions/cross_domain
    // crossDomain,
    // 静态文件托管 https://midwayjs.org/docs/extensions/static_file
    staticFile,
    // orm https://midwayjs.org/docs/extensions/orm
    orm,
    // 参数验证 https://midwayjs.org/docs/extensions/validate
    validate,
    // 本地任务 http://www.midwayjs.org/docs/extensions/cron
    cron,
    // 文件上传
    upload,
    // cool-admin 官方组件 https://cool-js.com
    cool,
    // rpc 微服务 远程调用
    // rpc,
    // 任务与队列
    task,
    // 即时通讯
    socketio,
    {
      component: info,
      enabledEnvironment: ['local', 'prod'],
    },
    view,
  ],
  importConfigs: [
    {
      default: DefaultConfig,
      local: LocalConfig,
      prod: ProdConfig,
    },
  ],
})
export class MainConfiguration implements ILifeCycle {
  @App()
  app: IMidwayApplication;

  @Inject()
  webRouterService: MidwayWebRouterService;

  @Inject()
  logger: ILogger;

  @Inject()
  environmentService: MidwayEnvironmentService;

  @InjectDataSource() // 默认 (MySQL)
  dataSource: DataSource;

  // @Inject() // 可以注入 OracleService 如果需要在 onReady 中显式操作
  // oracleService: OracleService;

  async onReady() {
    this.logger.info(`Application environment: ${this.environmentService.getCurrentEnvironment()}`);

    // 检查并初始化默认 DataSource (MySQL)
    this.logger.info('Checking Default DataSource injected directly into MainConfiguration:', this.dataSource ? 'Available' : 'Unavailable');
    if (this.dataSource && !this.dataSource.isInitialized) {
        try {
            await this.dataSource.initialize();
            this.logger.info('Default DataSource initialized successfully in MainConfiguration.');
        } catch (error) {
            this.logger.error('Error initializing Default DataSource in MainConfiguration:', error);
        }
    } else if (this.dataSource && this.dataSource.isInitialized) {
         this.logger.info('Default DataSource was already initialized.');
    } else if (!this.dataSource) {
      this.logger.error('Default DataSource is null or undefined in MainConfiguration!');
    }

    // 初始化 ProcedureGenerator (依赖默认 DataSource)
    if (this.dataSource && this.dataSource.isInitialized) {
        try {
          this.logger.info('Attempting to get ProcedureGenerator...');
          const procedureGenerator = await this.app
            .getApplicationContext()
            .getAsync(ProcedureGenerator);
          this.logger.info('ProcedureGenerator instance obtained.');
          // 确保 ProcedureGenerator 内部的 DataSource 注入也正常
          if ((procedureGenerator as any).dataSource) {
            this.logger.info('DataSource seems available within ProcedureGenerator.');
            await procedureGenerator.init();
            this.logger.info('ProcedureGenerator init called.');
          } else {
            this.logger.error('DataSource is NOT available within ProcedureGenerator!');
          }
        } catch (error) {
          this.logger.error('Error getting or initializing ProcedureGenerator:', error);
        }
    } else {
         this.logger.warn('Skipping ProcedureGenerator initialization because Default DataSource failed to initialize.');
    }

    // （可选）如果需要确保 OracleService 在启动时初始化
    // try {
    //    this.logger.info('Triggering OracleService initialization...');
    //    await this.app.getApplicationContext().getAsync(OracleService); // 获取实例会触发 @Init
    //    this.logger.info('OracleService should be initializing/initialized.');
    // } catch (error) {
    //    this.logger.error('Error getting OracleService instance:', error);
    // }

    this.logger.info('Application is ready.');
  }
}
